package com.medical.data.service.impl;

import com.medical.data.component.LoginUserThreadLocal;
import com.medical.data.config.RedisCache;
import com.medical.data.domain.User;
import com.medical.data.exception.MyException;
import com.medical.data.service.TokenSerivce;
import com.medical.data.utils.JwtUtils;
import com.medical.data.utils.ResultCode;
import com.medical.data.vo.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Service("tokenSerivce")
@Slf4j
public class TokenSerivceImpl implements TokenSerivce {


    @Autowired
    private RedisCache redisCache;
    @Override
    public LoginUser getLoginUser(HttpServletRequest request) {
        //首先验证token是否有效
        boolean checkToken = JwtUtils.checkToken(request);
        if (!checkToken){
            return null;
        }
        String token = request.getHeader("token");
        //从redis取出
        LoginUser loginUser = redisCache.getCacheObject(token);
        return loginUser;
    }

    @Override
    public User getUser() {
        User user = LoginUserThreadLocal.get().getUser();
        if (ObjectUtils.isEmpty(user)) {
            throw new MyException(ResultCode.ERROR.getCode(), "用户不存在");
        }
        return user;
    }

    @Override
    public void setLoginUser(String jwtToken, LoginUser loginUser) {
        //将loginUser设置进去,设置有时间,按照token过期时间设置
        if (StringUtils.isNotBlank(jwtToken)&& ObjectUtils.isNotEmpty(loginUser)){
            redisCache.setCacheObject(jwtToken,loginUser,7*60*60*1000,TimeUnit.MILLISECONDS);
        }
    }
}
